package com.lzq.mybatis.session;
import com.lzq.mybatis.binding.MapperProxy;
import com.lzq.mybatis.conf.Configuration;
import com.lzq.mybatis.conf.MappedStatement;
import com.lzq.mybatis.executor.DefaultExecutor;
import com.lzq.mybatis.executor.Executor;
import java.lang.reflect.Proxy;
import java.util.List;

//对外提供访问的api
//将请求转发给executor
public class DefaultSqlSession implements sqlSession{
    private final Configuration conf;
    private Executor executor;
    public DefaultSqlSession(Configuration conf) {
        this.conf = conf;
        executor = new DefaultExecutor(conf);
    }
    //statement == sourceid == namespace + id
    public <E> List<E> selectList(String statement,Object parameters){
        MappedStatement ms = conf.getMappedStatements().get(statement);
        return executor.query(ms,parameters);
    }

    //查询一条记录
    public <T> T selectOne(String statement, Object parameters) {
        List<Object> res = this.selectList(statement,parameters);
        if(res == null && res.size() == 0){
            return null;
        }else if(res.size() == 1){
            return (T) res.get(0);
        }else{
            throw new RuntimeException("查询有多条记录");
        }
    }

    //通过动态代理实现面向接口的编程模型
    public <T> T getMapper(Class<T> type){
        MapperProxy mp = new MapperProxy(this);
        return (T) Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},mp);
    }
}
